// config.cpp
#include "config.h"
#include <fstream>
#include <algorithm>
#include <cctype>
#include <iostream>

std::string Config::m_filepath = Config::initialize_filepath();

Config &Config::getInstance()
{
    static Config instance;
    return instance;
}
Config::Config()
{
    parse();
}
void Config::trim(std::string &str)
{
    // 去除左边空格
    str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](unsigned char ch)
                                        { return !std::isspace(ch); }));

    // 去除右边空格
    str.erase(std::find_if(str.rbegin(), str.rend(), [](unsigned char ch)
                           { return !std::isspace(ch); })
                  .base(),
              str.end());
}

void Config::parse()
{
    std::ifstream file(m_filepath);
    if (!file.is_open())
    {
        std::cout << "Could not open config file: " + m_filepath + ". Creating default config file..." << std::endl;
        setDefaultConfig();
        return;
    }

    std::string line;

    while (std::getline(file, line))
    {
        trim(line);

        // 忽略空行或注释
        if (line.empty() || line[0] == ';' || line[0] == '#')
        {
            continue;
        }

        // 处理键值对 key = value
        size_t delimiter_pos = line.find('=');
        if (delimiter_pos != std::string::npos)
        {
            std::string key = line.substr(0, delimiter_pos);
            std::string value = line.substr(delimiter_pos + 1);
            trim(key);
            trim(value);

            if (!key.empty())
            {
                m_data[key] = value;
            }
        }
    }
    file.close();
    is_init = true;
}

void Config::setDefaultConfig()
{
    try
    {
        std::map<std::string, std::string> default_config = {
            {"port", "7092"},
            {"user", "root"},
            {"password", "root"},
            {"max_connections", "10"},
            {"charset", "utf8"},
            {"max_retries", "3"},
            {"retry_interval", "1000"},
            {"log_file", "db.log"},
            {"log_dir", "logs"},
            {"host", "127.0.0.1"}};
        std::filesystem::path path(m_filepath);
        std::filesystem::create_directories(path.parent_path());
        std::ofstream file(m_filepath);
        if (!file.is_open())
        {
            throw std::runtime_error("Could not open config file: " + m_filepath);
        }
        for (auto it = default_config.begin(); it != default_config.end(); ++it)
        {
            file << it->first << " = " << it->second << std::endl;
        }
        file.close();
        m_data = std::move(default_config);
        is_init = true;
        std::cout << "DEFAULT Config file created successfully." << std::endl;
    }
    catch (const std::exception &e)
    {
        std::cerr << "Set default config file failed:" << e.what() << std::endl;
    }
}